import { fetchHome } from '../../services/home/home';
import { fetchGoodsPageList, fetchCategory } from '../../services/good/index';
import { fetchShopMapInfos } from '../../services/usercenter/fetchShopMap'
import { checkPermission } from '../../utils/permissionUtil';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    scrollTop: 0,
    placeholderTxt: '',
    locationInfo: {
      hasPermission: false,
      locationListener: null,
      location: null,
      shopLocation: null,
      shopName: '未知',
      distance: '未知',
    },
    swipers: [],
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    pagePagination: {
      page: 1,
      size: 10,
      total: 0,
    },
    notic: {
      show: false,
      title: '提示',
      content: '本产品目前仅为了展示商品信息，暂不支持在线购买功能。如有购买需求，可在个人中心联系客服，或到线下门店咨询。\n\n该产品处于初始阶段，部分功能未开放。',
      confirmBtn: '已了解',
    }
  },
  goodListPagination: {
    index: 0,
    num: 10,
  },


  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    // TODO
    // this.setData({ "notic.show": true })
    this.init();
  },

  onPageScroll(e) {
    const scrollTop = e.scrollTop;
    this.setData({ scrollTop });
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      console.log('onReachBottom')
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    console.log('onPullDownRefresh')
    this.init();
  },

  init() {
    this.setData({ placeholderTxt: '新品-内室玻璃门' })
    this.loadHomePage();
    // this.loadShopInfo();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    fetchCategory().then((res) => {
      // const tabList = res.data;
      const tabList = res.data.map(item => ({
        text: item.name,
        key: item.groupId
      }))
      tabList.unshift({ text: '精品推荐', key: 0 })
      console.log('tabList: ', tabList)
      this.setData({ tabList })

    })
    fetchHome().then(({ swiper, tabList }) => {
      console.log('fetchHomet.abList: ', tabList)
      let imgSrcs = [];
      swiper.filter(e => imgSrcs.push(e.img))
      this.setData({
        // tabList,
        swipers: swiper,
        imgSrcs: imgSrcs,
        pageLoading: false,
      });
      console.log('fetchHome end...')
      this.loadGoodsList(true);
    });
  },

  tabChangeHandle(e) {
    // TODO
    const { value, label } = e.detail;
    // this.privateData.tabIndex = e.detail;
    // console.log('tabChangeHandle: ', value, label, this.privateData.tabIndex)
    const scrollTop = this.data.scrollTop;
    let param = {};
    if (value !== 0) {
      param = { typeId: value }
    }
    if (scrollTop > 300) {
      this.loadGoodsList(true, 235, param);
    } else {
      console.log('tabChangeHandle < 300')
      this.loadGoodsList(true, 0, param);
    }
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false, scrollTop = 0, param = {}) {
    console.log('loadGoodsList', fresh, scrollTop)
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: scrollTop,
      });
    }
    this.setData({ goodsListLoadStatus: 1 });
    let pagePagination = this.data.pagePagination;
    if (fresh) {
      pagePagination.page = 0;
      pagePagination.total = 0;
    }
    if (pagePagination.page * pagePagination.size >= pagePagination.total && pagePagination.total != 0) {
      console.log('no more goods...')
      this.setData({ goodsListLoadStatus: 2 })
      return;
    }
    pagePagination.page = pagePagination.page + 1;

    try {
      const params = {
        pageNum: pagePagination.page,
        oageSize: pagePagination.size,
        ...param
      }
      // if 
      console.log('param', params)
      const info = await fetchGoodsPageList(params);
      console.log('info', info)
      // pagePagination.page = info.page;
      pagePagination.total = info.total;
      let status = pagePagination.page * pagePagination.size >= pagePagination.total ? 2 : 0;
      let rows = info.rows;
      if (rows) {
        rows.filter(e => e.tags = ["限时抢购"])
      }
      this.setData({
        goodsList: fresh ? rows : this.data.goodsList.concat(rows),
        goodsListLoadStatus: status,
        pagePagination,
      });
    } catch (err) {
      console.log(err)
      this.setData({ goodsListLoadStatus: 3 });
    }
  },

  goodListClickHandle(e) {
    console.log(e.detail)
    const { gNumber } = e.detail;
    console.log('goodListClickHandle spuId: ', gNumber)
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${gNumber}`,
    });
  },

  toastMsg(message) {
    Toast({
      context: this,
      selector: '#t-toast',
      message,
    });
  },

  navToSearchPage() {
    console.log('navToSearchPage...')
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },
  navToLocationPage() {
    // this.checkLocationPermission();
  },

  navToActivityDetail({ detail }) {
    const { index: promotionID = 0 } = detail || {};
    const swiper = this.data.swipers[promotionID];
    if (swiper.navigateTo) {
      wx.navigateTo({ url: swiper.navigateTo })
    } else if (!swiper.noNavigateTo) {
      wx.navigateTo({
        url: `/pages/promotion-detail/index?promotion_id=${swiper.id}`,
      });
    }
  },

  onToTop(e) {
    this.triggerEvent('to-top', e);
  },

  closeDialog() {
    this.setData({ "notic.show": false })
  },

  loadShopInfo() {
    console.log('loadShopInfo...');
    fetchShopMapInfos().then(
      ({ addressInfos }) => {
        let addressInfo = addressInfos[0];
        const info = {
          longitude: addressInfo.location.lng,//中心经度
          latitude: addressInfo.location.lat,//中心纬度
          address: addressInfo.address,
          name: addressInfo.name
        }
        this.setData({ 'locationInfo.shopLocation': info, 'locationInfo.shopName': addressInfo.name });
        this.getLocation();
      }
    );
  },

  getLocation() {
    console.log('getLocation...')
    checkPermission({ code: 'scope.userLocation', name: '定位信息' }).then(res => {
      console.log('checkPermission...', res)
      this.getLocationInfo();
    })
      .error(err => {
        console.error('no lacation permission', err)
      })
    // console.log('asdasda... ', checkPermission({ code: 'scope.userLocation', name: '定位信息' }))
    // if (checkPermission({ code: 'scope.userLocation', name: '定位信息' })) {
    //   console.log('can get user loacation...')
    //   this.getLocation();
    //   const { location, shopLocation } = this.locationInfo;
    //   if (location && shopLocation) {
    //     const distance = calculateDistance();
    //     this.setData({ 'locationInfo.distance': distance });
    //   } else {
    //     this.setData({ 'locationInfo.distance': '未知' });
    //   }
    // }
  },

  // 直接获取定位信息
  getLocationInfo() {
    // this.startLocationChangeListening();
    this.getWXLocation();
  },
  getWXLocation() {
    // 获取用户的位置信息
    wx.getLocation({
      type: 'wgs84', // 返回 GPS 坐标
      success: (res) => {
        console.log('getLocation: ', res)
        const latitude = res.latitude;
        const longitude = res.longitude;
        const altitude = res.altitude;
        this.setData({
          'locationInfo.location': {
            latitude,
            longitude,
            altitude,
          },
          'locationInfo.hasPermission': true
        });
        console.log('定位信息:', this.data.location);
      },
      fail: (err) => {
        console.error('获取位置信息失败', err);
        this.toastMsg('获取位置信息失败');
      }
    });
  },

  // 启动地理位置监听
  startLocationChangeListening() {
    console.log('startLocationChangeListening')
    // 开始监听地理位置变化
    this.setData({
      hasPermission: true
    });

    // 启动地理位置监听
    const _locationListener = (res) => {
      console.log('locationListener >> ', res)
      const latitude = res.latitude;
      const longitude = res.longitude;
      const altitude = res.altitude;
      this.setData({
        'locationInfo.location': {
          latitude,
          longitude,
          altitude,
        },
        'locationInfo.hasPermission': true
      });
      console.log('定位信息:', this.data.location);
    };

    // 设置地理位置监听
    wx.onLocationChange(_locationListener);
    wx.offLocationChange(_locationListener)

    // 保存监听器以便在页面卸载时移除
    this.setData({
      'locationInfo.locationListener': _locationListener
    });
  },

});
